package cn.cs.controller;

import cn.cs.common.*;
import cn.cs.pojo.AfterOrder;
import cn.cs.pojo.AppOrder;
import cn.cs.pojo.RepOrder;
import cn.cs.service.AfterOrderService;
import cn.cs.service.AppOrderService;
import cn.cs.service.RepairOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static cn.cs.common.DtoUtil.*;

@Controller
@RequestMapping(value = "/afterOrder")
public class AfterOrderController {
    @Autowired
    private AfterOrderService afterOrderService;

    @Resource
    private RepairOrderService repairOrderService;

    @Resource
    private AppOrderService appOrderService;

    /****
     * 获取维修售后列表信息
     * @param
     * @param
     * @return
     */
    @RequestMapping("/getAllAfterOrder")
    @ResponseBody
    public Dto getAllAfterOrder(HttpServletRequest request, HttpServletResponse response) {
        Dto dto = null;
        try {
            String token = request.getHeader("token");
            response.setHeader("Access-Control-Allow-Origin", "*");
            dto = afterOrderService.getAllAfterOrder(request);
        } catch (Exception e) {
            e.printStackTrace();
            return returnFail("获取失败", "0002");
        }
        return dto;
    }

    /****
     * 确认和处理
     * @param
     * @param
     * @return
     */
    @RequestMapping("/confirmAndHandle")
    @ResponseBody
    public Dto confirmAndHandle(HttpServletRequest request, HttpServletResponse response) {
        Dto dto = null;
        try {
            String token = request.getHeader("token");
            response.setHeader("Access-Control-Allow-Origin", "*");
            dto = afterOrderService.confirm(request);
        } catch (Exception e) {
            e.printStackTrace();
            return returnFail("获取失败", "0002");
        }
        return dto;
    }

    /****
     * 已读
     * @param
     * @param
     * @return
     */
    @RequestMapping("/readShMsg")
    @ResponseBody
    public Dto readShMsg(HttpServletRequest request, HttpServletResponse response) {
        Dto dto = null;
        try {
            String token = request.getHeader("token");
            response.setHeader("Access-Control-Allow-Origin", "*");
            dto = afterOrderService.readShMsg(request);
        } catch (Exception e) {
            e.printStackTrace();
            return returnFail("获取失败", "0002");
        }
        return dto;
    }


    /**
     * 发起售后申请
     *
     * @param orderId
     * @param userId
     * @param repairUserId
     * @param orderDate
     * @param orderTime
     * @param account
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/wxApi/registerAppOrder")
    @Transactional
    public Dto registerAppOrder(String orderId, String userId, String repairUserId,
                                String orderDate, String orderTime, String account) throws Exception {
        AfterOrder after = afterOrderService.getAfterOrderByOrderIdOne(orderId);
        if (EmptyUtils.isEmpty(userId)) {
            return DtoUtil.returnFail("用户不存在，请重新授权登陆", "userNull001");
        }
        if (EmptyUtils.isNotEmpty(after)) {
            String state = after.getState();
            if (EmptyUtils.isNotEmpty(state)) {
                if ("0".equals(state) || "1".equals(state)) {
                    return DtoUtil.returnFail("您的售后申请未结束，暂不能重新下单", "003");
                }
            }
        }
        AfterOrder afterOrder = new AfterOrder();
        String id = IdWorker.getId();
        afterOrder.setId(id);
        afterOrder.setOrderId(orderId);
        afterOrder.setUserId(userId);
        afterOrder.setRepairUserId(repairUserId);
        afterOrder.setOrderTime(orderTime);
        afterOrder.setAccount(account);
        afterOrder.setIsread("0");
        afterOrder.setCreateDate(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        //预约日期  -- 转变为时间
        if ("今天".equals(orderDate)) {
            afterOrder.setOrderDate(DateUtil.format(new Date(), "yyyy-MM-dd"));
        } else if ("明天".equals(orderDate)) {
            afterOrder.setOrderDate(DateUtil.getFetureDate(1));
        } else if ("后天".equals(orderDate)) {
            afterOrder.setOrderDate(DateUtil.getFetureDate(2));
        }
        try {
            afterOrderService.addAfterOrder(afterOrder);
            // 发送极光推送给维修工
            String[] strSelect = new String[1];
            Map<String, String> cmap = new HashMap<String, String>();
            cmap.put("afterOrderToRepairUser", id);
            strSelect[0] = repairUserId;
            Object obj = JPushUtil.testSendPush(strSelect, "您有新的售后订单，请查看", cmap);
            System.out.println(obj);
            return DtoUtil.returnSuccess("申请售后成功", id);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("操作失败，请重试", "002");
        }

    }


    /**
     * 根据订单号，用户Id查询售后单
     *
     * @param orderId
     * @param userId
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/wxApi/getAfterOrderByUserId")
    public Dto getAfterOrderByUserId(String orderId, String userId) throws Exception {
        if (EmptyUtils.isEmpty(userId)) {
            return DtoUtil.returnFail("用户不存在，请重新授权登陆", "userNull001");
        }
        return DtoUtil.returnSuccess("获取售后订单成功", afterOrderService.getAfterOrderByUserIdAndOrderId(orderId, userId));
    }

    /**
     * 根据订单号，用户Id查询售后单 新
     *
     * @param orderId
     * @param userId
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/wxApi/getAfterOrderByOrderIdUserId")
    public Dto getAfterOrderByOrderIdUserId(String orderId, String userId, String id) throws Exception {
        return DtoUtil.returnSuccess("获取售后订单成功", afterOrderService.getAfterOrderByUserId(orderId, userId, id));
    }


    /**
     * 重新下单成功（用户通过售后下单给原单的维修工）
     *
     * @param id
     * @param appOrderId
     * @param orderDate
     * @param orderTime
     * @param repairNumber
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/wxApi/againSaveAppOrder")
    @Transactional
    public Dto againSaveAppOrder(String id, String appOrderId, String orderDate, String orderTime, String repairNumber,
                                 String userAddressId, String hasElevator, String floorNumber, String faultType, String faultCategory,
                                 String faultComment, String isprivateWork, String userType, String is_protect, String companyName, String userName,
                                 String userPhone, String provinceName, String cityName, String areaName,
                                 String addressContent, String common_failures) throws Exception {

        AppOrder appOrderMap = appOrderService.getAppOrderById(appOrderId);
        Map<String, Object> repairOrderMap = repairOrderService.getOrderByAppOrderId(appOrderId);
        AppOrder appOrder = new AppOrder();
        String newId = IdWorker.getId();
        String createTime = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
        appOrder.setId(newId);
        appOrder.setCreateTime(createTime);
        appOrder.setCommonFailures(common_failures);
        appOrder.setAfterOrderId(id);

        //预约日期  -- 转变为时间
        if ("今天".equals(orderDate)) {
            appOrder.setOrderDate(DateUtil.format(new Date(), "yyyy-MM-dd"));
        } else if ("明天".equals(orderDate)) {
            appOrder.setOrderDate(DateUtil.getFetureDate(1));
        } else if ("后天".equals(orderDate)) {
            appOrder.setOrderDate(DateUtil.getFetureDate(2));
        }

        appOrder.setOrderTime(orderTime);
        appOrder.setFloorNum(floorNumber);
        appOrder.setFaultType(appOrderMap.getFault_type());
        appOrder.setFaultCategory(appOrderMap.getFault_category());
        appOrder.setHasElevator(hasElevator);
        appOrder.setFaultComment(faultComment);
        appOrder.setCreateTime(createTime);
        appOrder.setOrderState("1");
        appOrder.setUserType(userType);
        appOrder.setUserId(appOrderMap.getUser_id());
        appOrder.setIsprivateWork("0");
        appOrder.setIs_again_order("1");

        appOrder.setUserAddress(areaName + " " + addressContent);
        appOrder.setUserName(userName);
        appOrder.setUserPhone(userPhone);
        appOrder.setUserAddressId(appOrderMap.getUser_address_id());
        if ("0".equals(userType)) {
            appOrder.setRepairNumber(Integer.valueOf(repairNumber));
            appOrder.setCompanyName(companyName);
        } else if ("2".equals(userType)) {
            appOrder.setIs_protect(is_protect);
            appOrder.setCompanyName(companyName);
        }

        RepOrder repOrder = new RepOrder();
        repOrder.setId(IdWorker.getId());
        repOrder.setApp_order_id(newId);
        repOrder.setUserId(String.valueOf(appOrderMap.getUser_id()));
        repOrder.setRepUserId(String.valueOf(repairOrderMap.get("rep_user_id")));
        repOrder.setOrderState("0");
        repOrder.setCreateTime(createTime);

        int i = appOrderService.itriptxAddAppOrder(appOrder);
        int j = repairOrderService.addRepairOrder(repOrder);
        if (i == 1 && j == 1) {
            AfterOrder afterOrder = new AfterOrder();
            afterOrder.setId(id);
            afterOrder.setState("4");
            afterOrderService.modifyAfterOrder(afterOrder);
            return DtoUtil.returnSuccess("重复下单成功", appOrderId);
        } else {
            return DtoUtil.returnFail("重复下单失败，请重试", "002");
        }

    }

    /**
     * 取消售后订单
     *
     * @param
     * @param
     * @return
     */
    @RequestMapping("/wxApi/cancelAfterOrder")
    @ResponseBody
    public Dto cancelAfterOrder(String id, String state) throws Exception {
        state = "0".equals(state) ? "-1" : "-2";//0未接单 1维修工知晓 当前状态 修改为 -2已取消(维修工知晓后取消) -1已取消(直接取消)
        AfterOrder afterOrder = new AfterOrder();
        afterOrder.setId(id);
        afterOrder.setState(state);
        afterOrder.setCancelDate(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        return DtoUtil.returnSuccess("取消成功", afterOrderService.modifyAfterOrder(afterOrder));
    }


    /**
     * 分页查询 未处理完成的售后申请
     *
     * @param pageNumber
     * @param pageSize
     * @return
     * @throws Exception TODO 添加搜索
     */
    @RequestMapping(value = "/p/getAfterOrderList")
    public Dto getAfterOrderList(Integer pageNumber, Integer pageSize) throws Exception {
        Map<String, Object> param = new HashMap<String, Object>();
        return DtoUtil.returnSuccess("获取成功", afterOrderService.queryAfterOrderPageByMap(param, pageNumber, pageSize));
    }

    /**
     * 分页查询 未处理完成的售后申请
     *
     * @param pageNumber
     * @param pageSize
     * @return
     * @throws Exception TODO 添加搜索
     */
    @RequestMapping(value = "/p/getAfterOrderAllList")
    public Dto getAfterOrderAllList(Integer pageNumber, Integer pageSize) throws Exception {
        Map<String, Object> param = new HashMap<String, Object>();
        return DtoUtil.returnSuccess("获取成功", afterOrderService.getAfterOrderAllListPage(param, pageNumber, pageSize));
    }


}
